package com.sdhs.common.service;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.sdhs.common.constant.Constant;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import com.sdhs.common.page.PageData;
import com.sdhs.common.utils.ConvertUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

public abstract class BaseServiceExt<M extends BaseMapper<T>, T> extends ServiceImpl<M, T> {

    protected Logger logger = LoggerFactory.getLogger(getClass());



    public String baseBoolean2String(String value) {
        if (StringUtils.isEmpty(value)) {return "0";}
        if ("true".equals(value)) {return "1";}
        if ("false".equals(value)) {return "0";}
        if ("1".equals(value)) {return "1";}
        return "0";

    }

    /**
     * 获取分页对象
     * @param params      分页查询参数
     * @param defaultOrderField  默认排序字段
     * @param isAsc              排序方式
     */
    protected  IPage<T> getPage(Map<String, Object> params, String defaultOrderField, boolean isAsc) {
        //分页参数
        long curPage = 1;
        long limit = 10;

        if (params.get(Constant.PAGE) != null) {
            curPage = Long.parseLong((String) params.get(Constant.PAGE));
        }
        if (params.get(Constant.LIMIT) != null) {
            limit = Long.parseLong((String) params.get(Constant.LIMIT));
        }

        //分页对象
        Page<T> page = new Page<>(curPage, limit);

        //分页参数
        params.put(Constant.PAGE, page);

        //排序字段
        String orderField = (String) params.get(Constant.ORDER_FIELD);
        String order = (String) params.get(Constant.ORDER);

        //前端字段排序
        if (com.baomidou.mybatisplus.core.toolkit.StringUtils.isNotEmpty(orderField)
                && com.baomidou.mybatisplus.core.toolkit.StringUtils.isNotEmpty(order)) {
            OrderItem orderItem = new OrderItem();
            orderItem.setAsc(Constant.ASC.equalsIgnoreCase(order));
            orderItem.setColumn(orderField);
            page.addOrder(orderItem);
        }

        //默认排序
        OrderItem orderItem = new OrderItem();
        orderItem.setAsc(isAsc);
        orderItem.setColumn(defaultOrderField);
        page.addOrder(orderItem);
        return page;
    }

    /**
     * 获取分页对象
     * @param params      分页查询参数
     * @param defaultOrderField  默认排序字段
     * @param isAsc              排序方式
     */
    protected <T> IPage<T> getPage(Map<String, Object> params, String defaultOrderField, boolean isAsc, Class<T> resultType) {
        //分页参数
        long curPage = 1;
        long limit = 10;

        if (params.get(Constant.PAGE) != null) {
            curPage = Long.parseLong((String) params.get(Constant.PAGE));
        }
        if (params.get(Constant.LIMIT) != null) {
            limit = Long.parseLong((String) params.get(Constant.LIMIT));
        }

        //分页对象
        Page<T> page = new Page<>(curPage, limit);

        //分页参数
        params.put(Constant.PAGE, page);

        //排序字段
        String orderField = (String) params.get(Constant.ORDER_FIELD);
        String order = (String) params.get(Constant.ORDER);

        //前端字段排序
        if (com.baomidou.mybatisplus.core.toolkit.StringUtils.isNotEmpty(orderField)
                && com.baomidou.mybatisplus.core.toolkit.StringUtils.isNotEmpty(order)) {
            OrderItem orderItem = new OrderItem();
            orderItem.setAsc(Constant.ASC.equalsIgnoreCase(order));
            orderItem.setColumn(orderField);
            page.addOrder(orderItem);
        }

        //默认排序
        OrderItem orderItem = new OrderItem();
        orderItem.setAsc(isAsc);
        orderItem.setColumn(defaultOrderField);
        page.addOrder(orderItem);
        return page;
    }

    protected <T> PageData<T> getPageData(List<?> list, long total, Class<T> target) {
        List<T> targetList = ConvertUtils.sourceToTarget(list, target);

        return new PageData<>(targetList, total);
    }

    protected <T> PageData<T> getPageData(IPage page, Class<T> target) {
        return getPageData(page.getRecords(), page.getTotal(), target);
    }

    protected  <T> QueryWrapper<T> getQueryWrapper(Map<String, Object> mapParam,Class<T> target,String ...likeFields) {
        QueryWrapper<T> queryWrapper =new QueryWrapper<>();
        List<String> 	likeFieldList=new ArrayList<>();
        Collections.addAll(likeFieldList,likeFields);
        installMplus(queryWrapper,mapParam,target,likeFieldList,null);
        return queryWrapper;
    }
    protected  <T> QueryWrapper<T> getQueryWrapper(Map<String, Object> mapParam, Class<T> target,List<String> likeFields,List<String> nullFields) {
        QueryWrapper<T> queryWrapper =new QueryWrapper<>();
        installMplus(queryWrapper,mapParam,target,likeFields,nullFields);
        return queryWrapper;
    }

    private  void installMplus(QueryWrapper<?> queryWrapper,Map<String, Object> searchMap,Class<?> target, List<String> likeFields,List<String> nullFields) {
        String name;
        Object value;
        for (Map.Entry<String, Object> entry : searchMap.entrySet()) {
            name=entry.getKey();
            value=entry.getValue();
            if (BeanUtils.getPropertyDescriptor(target,name)==null) {continue;}
            if (null != value && value instanceof Date) {
                addQueryByDate(queryWrapper, name, String.valueOf(value));
                continue;
            }

            if (null!=value &&  StringUtils.isNotBlank(String.valueOf(value)) && likeFields!=null && likeFields.contains(name)) {
                queryWrapper.like(name,String.valueOf(value));
                continue;
            }

            if (null !=value && StringUtils.isNotBlank(String.valueOf(value))) {
                queryWrapper.eq(name, value);
                continue;
            }

            if (nullFields!=null && nullFields.contains(name)) {
                queryWrapper.isNull(name);
            }

        }
    }

    /**
     * 获取日期类型的值,大于0点小于23:59
     * @param value
     * @return
     * @throws ParseException
     */
    private void addQueryByDate(QueryWrapper<?> queryWrapper, String name, String value) {
        Date date = null;
        SimpleDateFormat time =new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
        try {
            if (value.length() == 10) {
                //比较大于
                Date date1 = time.parse(value + " 00:00:00");
                //比较小于
                Date date2 =time.parse(value + " 23:59:59");
                //TODO 日期类型比较特殊 可能oracle下不一定好使
                queryWrapper.ge(name, date1).le(name, date2);
            } else {
                Date date1 = null;
                date1 = time.parse(value);
                queryWrapper.eq(name, date1);
            }
        } catch (ParseException e) {
            e.printStackTrace();
        }
    }
    protected Map<String, Object> paramsToLike(Map<String, Object> params, String... likes) {
        for (String like : likes) {
            String val = (String) params.get(like);
            if (com.baomidou.mybatisplus.core.toolkit.StringUtils.isNotEmpty(val)) {
                params.put(like, "%" + val + "%");
            } else {
                params.put(like, null);
            }
        }
        return params;
    }

    /**
     * 业务流程节点完成
     */
    public void baseProcessNodeFinish() {

    }
}